/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.core.eventbus;

import com.google.common.eventbus.Subscribe;
import com.lvyh.lightframe.core.cache.ServiceRegistryCache;
import com.lvyh.lightframe.common.RpcContext;
import com.lvyh.lightframe.core.config.ServerConfig;
import com.lvyh.lightframe.common.ext.ExtensionLoaderFactory;
import com.lvyh.lightframe.registry.Registry;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lvyh 2021/05/15.
 */
@EventBusListener
@Slf4j
public class ServerStateChangeListener {

    @Subscribe
    public void start(ServerStartedEvent event) throws InterruptedException {
        log.info("Server started, server config: {}", event.getServerConfig());
        ServerConfig serverConfig = event.getServerConfig();
        String serviceAddress = serverConfig.getIp() + ":" + serverConfig.getPort();
        Registry registry = ExtensionLoaderFactory.getExtensionLoader(Registry.class).
                getExtension(RpcContext.getRegistry(), new Class[]{String.class}, new Object[]{RpcContext.getZkAddress()});

        // Register RPC service address
        if (registry != null) {
            for (String interfaceName : ServiceRegistryCache.serviceCache.keySet()) {
                registry.register(interfaceName, serviceAddress);
                log.info("register service, interfaceName: [{}], serviceAddress: [{}]", interfaceName, serviceAddress);
            }
        }
    }

    @Subscribe
    public void stop(ServerStoppedEvent event) throws InterruptedException {
        log.info("Server stopped, server config: {}", event.getServerConfig());

        // Remove service
        for (String interfaceName : ServiceRegistryCache.serviceCache.keySet()) {
            ServiceRegistryCache.serviceCache.remove(interfaceName);
            log.info("remove service, interfaceName: [{}]", interfaceName);
        }
    }
}
